import sys
import pprint
import string
import sys
import cgi
import types
import traceback
import urllib

import genx_metaweb
import genx_transfill
import genx_helpers
import genx_errors
import bm_text
import bm_extract
import bm_cfg

import api_praized

from bm_log import Log

searchd = {
	"title" : "Companies",
	"source" : "Praized",
	"templated" : {
		"gencard-uf" : {
			"title" : "GenCard",
			"title_full" : "GenCard for Microformats",
			"caps" : [ 
				genx_helpers.CAP_GENCARD, 
				genx_helpers.CAP_HTML, 
				genx_helpers.CAP_MICROFORMATS, 
				genx_helpers.CAP_HCARD,
			],
		},
	},
}

CACHE = False

def query(cfg, searchd, name, application, retry = 0):
	api_key = bm_cfg.cfg.as_string("praized-merchants.api.key")
	slug = bm_cfg.cfg.as_string("praized-merchants.api.slug")

	api = api_praized.PraizedMerchants(api_key = api_key, slug = slug)
	api.SearchOn(
		q = name,
		l = "Toronto",
	)

	count = -1 
	for itemw in api.IterItems():
		count += 1
		if count >= 19:
			break

		iid = application.MakeIID(itemw.as_string('pid', otherwise = KeyError))

		if CACHE:
			data = application.Load(
				iid = iid,
				ctype = 'application/json'
			)
		else:
			data = None

		rd = None
		if data:
			try:
				rd = eval(data)
			except:
				traceback.print_exc(file = sys.stderr)

		if rd == None:
			rd = {
				genx_helpers.KEY_IID : iid,
				genx_helpers.KEY_TITLE_SHORT : itemw.as_string("name"),
				genx_helpers.KEY_TITLE_FULL : itemw.as_string("name"),
				genx_helpers.KEY_TITLE_LIST : itemw.as_string("name") or "[no name]",
			}

			mapping = [
				( "location.street_address", "street_address", ),
				( "location.city.name", "locality", ),
				( "location.regions.province", "region", ),
				( "location.country.name", "country_name", ),
				( "location.postal_code", "postal_code", ),
				( "phone", "tel", ),
				( "fax", "fax", ),
			]

			for path, key in mapping:
				value = itemw.as_string(path)
				if value:
					rd[key] = value

			lat = itemw.as_float("location.latitude", otherwise = None)
			lon = itemw.as_float("location.longitude", otherwise = None)
			if lat != None and lon != None:
				rd["geo"] = {
					"lat" : lat,
					"lon" : lon,
					"uzoom" : -15,
				}

		yield	rd
